package cn.lysoy.demo.dynamicDatasourceTest;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

/**
 * 简易动态数据源
 * @author 宋杨
 * @email s2295938761@163.com
 * @phone 15216839375
 * @date 2022/9/1
 */
public class MyDynamicDatasource {
    HashMap<String, MyDatasource> pools = new HashMap<>();

    //提供静态的私有的本类对象
    private static MyDynamicDatasource myDynamicConnectionPool;
    //构造方法私有化
    private MyDynamicDatasource(List<DynamicPoolProperties> dynamicPoolPropertiesList) {
        init(dynamicPoolPropertiesList);
    }
    //提供静态的可以获取本类对象的方法。
    public synchronized static MyDynamicDatasource getPool(List<DynamicPoolProperties> dynamicPoolPropertiesList) {
        if(myDynamicConnectionPool ==null)
            myDynamicConnectionPool = new MyDynamicDatasource(dynamicPoolPropertiesList);
        return myDynamicConnectionPool;
    };

    //成员属性初始化
    private void init(List<DynamicPoolProperties> dynamicPoolPropertiesList) {
        for (DynamicPoolProperties dynamicPoolProperties : dynamicPoolPropertiesList) {
            MyDatasource myDatasource = new MyDatasource(dynamicPoolProperties.getProperties());
            pools.put(dynamicPoolProperties.getName(), myDatasource);
        }
    }

    /**
     * 从池中获取一个可用的连接
     * @return
     */
    public Connection getConn(String key) throws SQLException {
        return pools.containsKey(key) ? pools.get(key).getConn() : null;
    }

    public class MyDatasource {
        MyDatasource(Properties properties) {
            DATASOURCE = new BasicDataSource();
            DATASOURCE.setDriverClassName(properties.getProperty("jdbc.driverclass"));
            DATASOURCE.setUrl(properties.getProperty("jdbc.url"));
            DATASOURCE.setUsername(properties.getProperty("jdbc.username"));
            DATASOURCE.setPassword(properties.getProperty("jdbc.password"));
            try {
                DATASOURCE.setInitialSize(new Integer(properties.getProperty("jdbc.initCount")));
            }catch (Exception e) {

            }
            try {
                DATASOURCE.setMinIdle(new Integer(properties.getProperty("jdbc.minCount")));
            }catch (Exception e) {

            }try {
                DATASOURCE.setMaxIdle(new Integer(properties.getProperty("jdbc.maxCount")));
            }catch (Exception e) {

            }
        }

        //创建连接池BasicDataSource
        private BasicDataSource DATASOURCE;

        public Connection getConn() throws SQLException {
            if(DATASOURCE==null)
                return null;
            return DATASOURCE.getConnection();
        }
    }
}
